package com.eastfair.imaster.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.base.BaseControllerInfo;
import com.eastfair.annotation.base.SubjectTypeEnum;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.config.dto.FormFieldDTO;
import com.eastfair.config.vo.ObjectFormFieldDetailVO;
import com.eastfair.config.vo.ObjectFormFieldEditVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.excel.analyze.ExcelAnalyze;
import com.eastfair.core.excel.analyze.ExcelReader;
import com.eastfair.core.excel.bean.ExcelAnalyzeResult;
import com.eastfair.core.excel.export.ExcelExport;
import com.eastfair.echo.core.EchoService;
import com.eastfair.imaster.dto.*;
import com.eastfair.imaster.entity.Exhibitor;
import com.eastfair.imaster.service.ExhibitorService;
import com.eastfair.imaster.vo.ExhibitorVo;
import com.eastfair.imaster.vo.ImasterVoGroupClass;
import com.eastfair.security.formfield.ConvertByFormField;
import com.eastfair.vo.VoGroupClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;
import static com.eastfair.core.exception.code.ExceptionCode.VISITOR_MOBILE_ERROR;


/**
 * <p>
 * 前端控制器
 * 展商
 * </p>
 *
 * @author ligang
 * @date 2021-09-07
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/exhibitor")
@Api(value = "Exhibitor", tags = "展商")
public class ExhibitorController extends SuperController<ExhibitorService, Long, Exhibitor, ExhibitorPageQuery, ExhibitorSaveDTO, ExhibitorUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Autowired
    private ExcelReader excelReader;

    @Autowired
    private UserAccountServiceFeign userAccountServiceFeign;

    @Autowired
    ConvertByFormField convertByFormField;

    @Override
    public void handlerResult(IPage<Exhibitor> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<Exhibitor> exhibitorList = list.stream().map((map) -> {
            Exhibitor exhibitor = Exhibitor.builder().build();
            //TODO 请在这里完成转换
            return exhibitor;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(exhibitorList));
    }


    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ExhibitorPageQuery> params) {
        ExhibitorPageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }
//    /**
//     * 添加展商
//     *
//     * @param exhibitorExcelDTO 组织实体
//     * @return
//     */
//    @ApiOperation(value = "添加展商", notes = "添加展商")
//    @PostMapping("/addExhibitor")
//    public R addExhibitor(@RequestBody ExhibitorExcelDTO exhibitorExcelDTO) {
//        List<ExhibitorExcelDTO> exhibitorExcelDTOList =  Arrays.asList(exhibitorExcelDTO);
//        //校验展商文件信息
//        String verifyStr = this.baseService.verifyExhibitor(ContextUtil.getExhibitionId(), ContextUtil.getProjectId(), exhibitorExcelDTOList);
//        if (StringUtils.isNotBlank(verifyStr) && verifyStr.length() > 0) {
//            return R.fail(verifyStr);
//        }
//        //执行导入
//        List<ExhibitorExcelResultDTO> exhibitorExcelResultDTOList = this.baseService.convertExhibitor(ContextUtil.getExhibitionId(), ContextUtil.getProjectId(), exhibitorExcelDTOList);
//        this.baseService.batchSave(ContextUtil.getExhibitionId(), ContextUtil.getProjectId(), exhibitorExcelResultDTOList);
//        return R.success("添加成功");
//    }


    /**
     * 添加展商
     *
     * @param exhibitorCompanyDTO 组织实体
     * @return
     */
    @ApiOperation(value = "添加展商", notes = "添加展商")
    @PostMapping("/addExhibitor")
    public R addExhibitor(@RequestBody ExhibitorCompanyDTO exhibitorCompanyDTO) {
        return this.baseService.addExhibitor(exhibitorCompanyDTO, ContextUtil.getProjectId());
    }

    /**
     * 修改展商
     *
     * @param exhibitorCompanyDTO 组织实体
     * @return
     */
    @ApiOperation(value = "修改展商", notes = "修改展商")
    @PutMapping("/updExhibitor")
    public R updExhibitor(@RequestBody ExhibitorCompanyDTO exhibitorCompanyDTO) {
        return this.baseService.addExhibitor(exhibitorCompanyDTO, ContextUtil.getProjectId());
    }

    /**
     * 修改展商
     *
     * @param editExhibitorDTO 组织实体
     * @return
     */
    @ApiOperation(value = "修改展商", notes = "修改展商")
    @PutMapping("/updExhibitorOfFormField")
    public R updExhibitorOfFormField(@RequestBody ExhibitorDTO editExhibitorDTO) {
        //组装数据
        ExhibitorCompanyDTO exhibitorCompanyDTO = null;
        R<ExhibitorVo> exhibitorVoR = convertByFormField.editFormFieldVOConvertObject(editExhibitorDTO.getObjectFormFieldEditVOList(),ExhibitorVo.class);
        if(SUCCESS_CODE == exhibitorVoR.getCode()){
            exhibitorCompanyDTO = new ExhibitorCompanyDTO();
            ExhibitorVo exhibitorVo = exhibitorVoR.getData();
            ExhibitorDTO exhibitorDTO = new ExhibitorDTO();
            BeanUtils.copyProperties(exhibitorVo,exhibitorDTO);
            exhibitorCompanyDTO.setExhibitorDTO(exhibitorDTO);
            CompanyDTO companyDTO = new CompanyDTO();
            BeanUtils.copyProperties(exhibitorVo.getCompanyVo(),companyDTO);
            exhibitorCompanyDTO.setCompanyDTO(companyDTO);
        }
        if(exhibitorCompanyDTO==null){
            return R.fail("更新失败");
        }
        return this.baseService.updExhibitor(exhibitorCompanyDTO, ContextUtil.getProjectId());
    }

    /**
     * 查询展商详情
     *
     * @param id 展商主键id
     * @return
     */
    @ApiOperation(value = "查询展商详情", notes = "查询展商详情")
    @GetMapping("/exhibitorDetail")
    @BaseControllerInfo()
    public R<ExhibitorVo> exhibitorDetail(Long id) {
        return R.success(baseService.exhibitorDetail(id));
    }

    /**
     * 查询展商详情
     * @param id 展商主键id
     * @return
     */
    @ApiOperation(value = "查询展商详情(只读)", notes = "查询展商详情(只读)")
    @GetMapping("/exhibitorDetailOfReadOnly")
    @BaseControllerInfo(isLanguageValue =true,voGroup={ImasterVoGroupClass.exhibitorDetailOfReadOnly.class})
    public R<ExhibitorVo> exhibitorDetailOfReadOnly(Long id) {
        return R.success(baseService.exhibitorDetail(id));
    }

    /**
     * 查询展商详情
     *
     * @param id 展商主键id
     * @return
     */
    @ApiOperation(value = "展商详情(修改场景)", notes = "展商详情(修改场景)")
    @GetMapping("/exhibitorDetailOfEdit")
    public R<List<ObjectFormFieldEditVO>> exhibitorDetailOfEdit(Long id) {
        ExhibitorVo exhibitorVo = baseService.exhibitorDetailOfEdit(id);
        // TODO: 2022/3/7 调用配置中心，按需返回结果
        FormFieldDTO formFieldDTO = new FormFieldDTO();
        formFieldDTO.setIsPerfectInfo(BusinessConstant.YES);
        formFieldDTO.setSubjectType(SubjectTypeEnum.ACTOR.name());
        R<List<ObjectFormFieldEditVO>> r = convertByFormField.objectConvertFormFieldEditVO(exhibitorVo, formFieldDTO);
//        R<ExhibitorVo> r1 = convertByFormField.formFieldVOConvertObject(r.getData(), ExhibitorVo.class);
        return r;
    }

    /**
     * 查询展商详情查看
     *
     * @param id 展商主键id
     * @return
     */
    @ApiOperation(value = "展商详情(查看场景)", notes = "展商详情(查看场景)")
    @GetMapping("/exhibitorDetailOfField")
    public R<List<ObjectFormFieldDetailVO>> exhibitorDetailOfField(Long id) {
        ExhibitorVo exhibitorVo = baseService.exhibitorDetailOfEdit(id);
        // TODO: 2022/3/7 调用配置中心，按需返回结果
        FormFieldDTO formFieldDTO = new FormFieldDTO();
//        formFieldDTO.setIsPerfectInfo(BusinessConstant.YES);
        formFieldDTO.setIsDetails(BusinessConstant.YES);
        formFieldDTO.setSubjectType(SubjectTypeEnum.ACTOR.name());
        R<List<ObjectFormFieldDetailVO>> r = convertByFormField.objectConvertFormFieldDetailVO(exhibitorVo, formFieldDTO);
        return r;
    }


    /**
     * 添加公司到展商
     *
     * @param exhibitorDTO 组织实体
     * @return
     */
    @ApiOperation(value = "添加公司到展商", notes = "创建节点组")
    @PostMapping("/addCompanyOfExhibitor")
    public R addCompanyOfExhibitor(@RequestBody @Validated({ExhibitorDTO.addCompanyOfExhibitor.class}) ExhibitorDTO exhibitorDTO) {

        return baseService.addCompanyOfExhibitor(exhibitorDTO);
    }

    /**
     * 展商剔除公司
     *
     * @param ids 组织实体
     * @return
     */
    @ApiOperation(value = "展商剔除公司", notes = "创建节点组")
    @DeleteMapping("/removeCompanyOfExhibitor")
    public R removeCompanyOfExhibitor(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            baseService.removeCompanyOfExhibitor(id);
        }
        return R.success();
    }


    /**
     * 查询展商下的公司以及展商员工
     *
     * @param id 展商主键id
     * @return
     */
    @ApiOperation(value = "查询展商下的公司以及展商员工", notes = "查询展商下的公司以及展商员工")
    @GetMapping("/findCompanyOfAll")
    public R<ExhibitorVo> findAllOfHost(Long id) {
        return R.success(baseService.findCompanyOfAll(id));
    }


    /**
     * 批量查询展商信息
     *
     * @param exhibitorDTO ids 展商id集合
     * @return
     */
    @ApiOperation(value = "批量查询展商信息", notes = "批量查询展商信息")
    @PostMapping("/queryByIdsOfAll")
    public R<List<ExhibitorVo>> queryByIds(@RequestBody ExhibitorDTO exhibitorDTO) {
        return R.success(baseService.queryByIds(exhibitorDTO.getIds()));
    }


    /**
     * 分页查询
     *
     * @param params 参数
     * @return 分页数据
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/queryPage")
    public R<Page<ExhibitorVo>> queryPage(@RequestBody PageParams<ExhibitorDTO> params) {
        return this.baseService.queryPage(params);
    }


    /**
     * 自定义分页查询
     *
     * @param params 参数
     * @return 分页数据
     */
    @ApiOperation(value = "自定义分页查询", notes = "自定义分页查询")
    @PostMapping("/queryPageDetails")
    public R<Page<ExhibitorVo>> queryPageDetails(@RequestBody PageParams<ExhibitorDTO> params) {
        return this.baseService.queryPageDetails(params);
    }

    /**
     * 描述：下载外部案件导入模板
     *
     * @throws Exception
     */
    @ApiOperation(value = "展商导出模版", notes = "展商导入模版")
    @PostMapping("/excelTemplateExport")
    public void excelTemplateExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("展商导入模版", "UTF-8") + ".xlsx");
        response.addHeader("fileName", URLEncoder.encode("展商导入模版", "UTF-8") + ".xlsx");
        ExcelExport.export(response.getOutputStream(), ExhibitorExcelDTO.HEADER, null);
    }

    @ApiOperation(value = "导入展商", notes = "导入问卷")
    @PostMapping("/importExcel")
    public R<String> importExcel(@RequestBody ExhibitorImportDTO exhibitorImportDTO) {
        Long projectId = ContextUtil.getProjectId();
        ExcelAnalyze<ExhibitorExcelDTO> analyze = new ExcelAnalyze<>(excelReader);
        ExcelAnalyzeResult<ExhibitorExcelDTO> analyzeResult = analyze.analyze(exhibitorImportDTO.getExcelUrl(), ExhibitorExcelDTO.class);
        if (Objects.isNull(analyzeResult)) {
            return R.fail("没有数据");
        }
        if (!analyzeResult.getSuccess()) {
            return R.fail("导入失败");
        }
        List<ExhibitorExcelDTO> exhibitorExcelDTOList = analyzeResult.getResultList();
        //校验展商文件信息
        String verifyStr = this.baseService.verifyExhibitor(exhibitorImportDTO.getExhibitionId(), projectId, exhibitorExcelDTOList);
        if (StringUtils.isNotBlank(verifyStr) && verifyStr.length() > 0) {
            return R.fail(verifyStr);
        }
        //执行导入
        List<ExhibitorExcelResultDTO> exhibitorExcelResultDTOList = this.baseService.convertExhibitor(exhibitorImportDTO.getExhibitionId(), projectId, exhibitorExcelDTOList);
        this.baseService.batchSave(exhibitorImportDTO.getExhibitionId(), projectId, exhibitorExcelResultDTOList);
        return R.success("导入成功");
    }

    /**
     * 测试
     *
     * @return
     */
    @ApiOperation(value = "测试", notes = "测试")
    @GetMapping("/test")
    public R<String> test() {
        ContextUtil.getProjectId();
        ContextUtil.getLanguageType();
        ContextUtil.getSubjectType();

        List<Exhibitor> exhibitorList = baseService.list(null, null);
//        R<String> r = userAccountServiceFeign.test();
//        log.info(JSON.toJSONString(r));
//        return R.success(null);
        return R.fail(VISITOR_MOBILE_ERROR);
    }


}
